<?php

namespace app\common\serve;


use function GuzzleHttp\default_ca_bundle;
use think\Db;

/**
 * 平台
 * Class Plat
 * @package app\common\serve
 */
class Plat extends Serve
{

    /**
     * 充值
     * @param $params
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function recharge($params)
    {
        if (!isset($params['money']) || $params['money'] < 1) {
            return ['code' => 0, 'msg' => '充值金额不得小于0'];
        }

        if (self::changeMoney($params['id'], 1, $params['money'], '管理员充值')) {
            return ['code' => 1, 'msg' => '充值成功'];
        } else {
            return ['code' => 0, 'msg' => '充值失败'];
        }
    }


    /**
     * 更新账户
     * @param $id
     * @param $type
     * @param $money
     * @param $info
     * @param int $target_uid
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function changeMoney($id, $type, $money, $info, $target_uid = 0)
    {
        $money = floatval($money);
        if (empty($money)) return false;

        $db = db('plat_money');
        $MM = $db->field('account_money,freeze_money')->where(['id' => $id])->find();
        if (!is_array($MM)) return false;

        $data['type'] = $type;
        $data['info'] = $info;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['create_ip'] = get_client_ip();

        switch ($type) {

            case 1 : //充值成功 +钱
            case 2: //手续费收入 +钱
                $data['affect_money'] = $money;
                $data['account_money'] = self::ifEmpty($MM['account_money']) + $money;
                $data['freeze_money'] = self::ifEmpty($MM['freeze_money']);
                break;

            case 3: //支付利息
            case 4 : //发放返佣
                $data['affect_money'] = $money;
                $data['account_money'] = self::ifEmpty($MM['account_money']) + ($money);
                $data['freeze_money'] = self::ifEmpty($MM['freeze_money']);
                break;

            default :
                return false;
                break;
        }

        Db::startTrans();

        $new_id = db('plat_money_log')->insertGetId($data);

        //帐户更新
        $xid = $db->where(['id' => $id])->update([
            'freeze_money' => $data['freeze_money'],
            'account_money' => $data['account_money']
        ]);

        if ($new_id && $xid) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }


        return true;
    }

    /**
     * 是否为空
     * @param $tar
     * @param int $def
     * @return int
     */
    public static function ifEmpty($tar, $def = 0)
    {
        return empty($tar) ? $def : $tar;
    }
}